<template>
  <div class="saoma">
    <div class="btn" @click="openCode">
      <slot></slot>
    </div>
    <!-- 扫码上传弹窗 -->
    <el-dialog title="扫码上传图片" :visible.sync="qrCodeShow" width="620px" append-to-body>
      <div ref="qrcode" v-if="qrCodeShow" style="width:200px; height:200px;margin:0 auto;margin-bottom:15px"></div>
      <div style="color:#999">{{Code_url}}</div>
      <div class="center">
        <el-button type="primary" @click="finishImg">上传完成，请点击此处</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { postUpload, creatrandomStr, closerandomStr } from "@/api/upload";
import QRCode from "qrcodejs2";
export default {
  props: {
    headers: {
      default: null,
    },
  },
  name: "saoma",
  data() {
    return {
      uuid: "",
      Code_url: "",
      qrCodeShow: false,
      qrcode: null,
      loading: false,
    };
  },

  created() {
    // this.getData();
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo;
    },
    retailDomain() {
      return this.$store.getters.retailDomain;
    },
  },
  methods: {
    async openCode() {
      if (this.loading) {
        return;
      } else {
        this.loading = true;
        this.uuid = this.generateUUID() + "---" + this.userInfo.tenantId;
        await creatrandomStr({ randomStr: this.uuid });
        this.Code_url = `${this.retailDomain["h5"].dictValue}pages/uploadImage/index/?uuid=${this.uuid}`;
        this.openPhoneCode();
        this.loading = false;
      }
    },
    // 生成二维码
    async openPhoneCode() {
      this.qrCodeShow = true;
      this.$nextTick(() => {
        if (this.qrcode != null) {
          this.qrcode.clear(); // 清除代码
          this.qrcode = null;
        } else {
        }
        this.qrcode = new QRCode(this.$refs.qrcode, {
          width: 200,
          height: 200,
          correctLevel: QRCode.CorrectLevel.L,
        });
        //生成二维码
        this.qrcode.makeCode(this.Code_url);
      });
    },
    // 获取图片
    async finishImg() {
      const res = await closerandomStr({ randomStr: this.uuid });
      if (res.data) {
        let arr = res.data[this.uuid];
        const resultArr = [];
        if (arr && arr.length) {
          arr.forEach((r) => {
            r.url = r.src;
            r.name = "";
            resultArr.push(r);
          });
        }
        this.qrCodeShow = false;
        this.$emit("success", resultArr);
      } else {
        this.qrCodeShow = false;
      }
    },
    // // 查询选号网的域名
    // async getData() {
    //   const r = await this.getDicts("retailDomain");
    //   if (r.data && r.data.length) {
    //     this.retailDomain = this.arrayToObject(r.data, "dictLabel");
    //   }
    // },
  },
};
</script>
<style scoped lang="scss">
</style>
